export function isEmpty(obj) {
  if (typeof obj === 'object' && obj !== null) {
    return Object.keys(obj).length === 0;
  } else {
    return obj === '' || obj === undefined || obj === null;
  }
}

export function sleep(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}

export function deepCopy(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  let newObj = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    newObj[key] = deepCopy(obj[key]);
  }
  return newObj;
}

export function generateRandomString(length) {
  var result = ''
  var characters = 'abcdefghijklmnopqrstuvwxyz0123456789'
  var charactersLength = characters.length
  for (var i = 0; i < length; i++) {
    result += characters.charAt(
      Math.floor(Math.random() * charactersLength)
    )
  }
  return result
}

export function generateUUIDv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

// 纯js导出数据到常规excel文件
export function exportData(list) {
  const data = list.map(item => {
    return {
      '姓名': item.name,
      '账号': item.account,
      '手机号': item.phone,
      '邮箱': item.email,
      '角色': item.role,
    }
  })

}

// js 随机数组中获取一个
export function getRandomElement(arr) {
  if (!Array.isArray(arr) || arr.length === 0) return undefined;
  const randomIndex = Math.floor(Math.random() * arr.length);
  return arr[randomIndex];
}

export function debounce(fn, wait) {
  let timeout = null;
  return function () {
    let context = this;
    let args = arguments;
    if (timeout) clearTimeout(timeout);
    let callNow = !timeout;
    timeout = setTimeout(() => {
      timeout = null;
    }, wait);
    if (callNow) fn.apply(context, args);
  };
}
export function DateFormat(date, fmt) {
  var o = {
    "M+": date.getMonth() + 1, //月份
    "D+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    "S": date.getMilliseconds() //毫秒
  };
  if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

export function GetDaysInMonth(datastr = '') {
  const now = new Date();
  console.log(now)
  const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
  return lastDay.getDate();
}

export function listToTree(arr) {
  let resArr = []
  arr.forEach(v => {
    let parentNode = arr.find(item => item.id == v.pid);
    if (parentNode) {
      // 如果没有找到父亲-说明 他是一级目录
      if (parentNode['children']) {
        parentNode['children'].push(v);
      } else {
        parentNode['children'] = [v];
      }
    } else {
      resArr.push(v)
    }
  });
  return resArr;
}


export function getTextWidth(text, fontSize = 12, fontWeight) {
  const ele = document.createElement('div');
  ele.style.position = 'absolute';
  ele.style.whiteSpace = 'nowrap';
  ele.style.fontSize = fontSize + 'px';
  ele.style.fontWeight = fontWeight;
  ele.innerText = text;
  document.body.append(ele);
  // 获取span的宽度
  const width = ele.getBoundingClientRect().width;
  // 从body中删除该span
  document.body.removeChild(ele);
  // 返回span宽度
  return width;
}


export function addEventListenerWrap(target, eventType, cb, option) {
  if (target && target.addEventListener) {
    target.addEventListener(eventType, cb, option);
  }
  return {
    remove: () => {
      if (target && target.removeEventListener) {
        target.removeEventListener(eventType, cb);
      }
    }
  };
}
